<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/4/22
 * Time: 13:23
 */

namespace app\admin\controller;


use org\Verify;
use think\Controller;
use app\admin\model\Admin as AdminModel;

class Login extends Controller
{
    /**
     * 登录页面
     * @return mixed
     */
    public function index(){
        return $this->fetch('/login');
    }

    // 登录操作
    public function doLogin()
    {
        $userName = input("param.user_name");
        $password = input("param.password");
        $code = input("param.code");

        if (empty($userName))return json(msg(-1, '', '用户名不能为空'));
        if (empty($password))return json(msg(-1, '', '密码不能为空'));
        if (empty($code))return json(msg(-1, '', '验证码不能为空'));

        $verify = new Verify();
        if (!$verify->check($code)) {
            return json(msg(-2, '', '验证码错误'));
        }

        $adminModel = new AdminModel();
        $hasAdmin = $adminModel->checkAdmin($userName);

        if(empty($hasAdmin)){
            return json(msg(-3, '', '管理员不存在'));
        }

        if(md5($password . config('salt')) != $hasAdmin['password']){
            return json(msg(-4, '', '密码错误'));
        }

        if(0 != $hasAdmin['status']){
            return json(msg(-5, '', '该账号被禁用'));
        }
        session('username', $hasAdmin['user_name']);
        session('id', $hasAdmin['id']);
        session('head', $hasAdmin['head']);

        // 更新管理员状态
        $param = [
            'login_count' => $hasAdmin['login_count'] + 1,
            'last_login_ip' => request()->ip(),
            'last_login_time' => time()
        ];

        $res = $adminModel->updateStatus($param, $hasAdmin['id']);

        if(1 != $res['code']){
            return json(msg(-6, '', $res['msg']));
        }
        // ['code' => 1, 'data' => url('index/index'), 'msg' => '登录成功']
        return json(msg(1, url('index/index'), '登录成功'));
    }

    public function checkVerify(){
        $verify = new Verify();
        $verify->imageH = 32;
        $verify->imageW = 100;
        $verify->length = 4;
        $verify->useNoise = false;
        $verify->fontSize = 14;
        return $verify->entry();
    }

    // 退出操作
    public function loginOut()
    {
        session('username', null);
        session('id', null);
        session('head', null);
        $this->redirect(url('index'));
    }
}